$(document).ready(function(){

// set the title of the first collapsible
//
$('.tab-observation').html('<span class="glyphicon glyphicon-plus gc_main_tabs_margin"></span>Add New Observation');

// hide record_id field in the first collapsible
//
$('.show_record_id').hide();

function quoteattr(s) {
    return ('' + s)
        .replace(/&/g, '&amp;')
        .replace(/'/g, '&apos;')
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

/***** Start - click delete record *******/

    $(document).on("click",".data_entry_delete",function(e){

        e.preventDefault();

        var id_record = $('input#id_record').val();

		var r = confirm("Delete this record?");
		if (r == false) {
			return;
		}

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-record-delete-json",
          dataType: "json",
          data: ({id_record : id_record}),

          success: function(data) {

			$('.show_record_id').hide();

			clear_form ();

			// reload content of the collapsible that show the records
			//
			$( ".getrecords" ).trigger( "click" );

          },
          error: function(data) {
             console.log(data);
             alert('Cant get id_record: ' + id_record + '. Try again.');
          }
        });
    });
/***** End - click delete record *******/

/***** Start - click edit record *******/
var at                        = [];
var edit_id_attribute_group = 0;

    $(document).on("click",".edit_record",function(e){

        e.preventDefault();

        var id_record = $(this).attr('id_record');

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-record-get-json",
          dataType: "json",
          data: ({id_record : id_record}),

          success: function(data) {

			// set id_attribute_group of this record
			//
             $('#id_attribute_group').removeAttr( "selected" );
             $('#id_attribute_group option[value="'+ data.id_attribute_group +'"]').attr('selected', 'selected');

             $('.show_record_id').show();
             $('.show_record_id').find('input').val(id_record);

			// fill array at with content of attribute_value of this record
			//
             attr = data.attribute_value;
             at = [];

             for (x in attr) {
				 at[attr[x].info.attribute_name] = attr[x].value;
			 }
			// open record additional attributes form
			//


             $('input#data_entry_li_content_species').val(data.title);
             $('input#id_item').val(data.id_item);
             $('input#id_record').val(data.id_record);

		     /* select record related project */
			 $('select#id_project option[value="'+data.id_project+'"]').attr("selected","selected");

			 edit_id_attribute_group = data.id_attribute_group;
			 $("#id_project").trigger( "change");



             //$(".getrecordattributes").trigger( "click" );

             $('input#data_entry_li_content_ref').val(formatter_latlong (data.ol_geometry));

             $('#data_entry_li_content_date').data("DateTimePicker").setDate(formatter_date (data.date_record_start));

             $( ".data_entry_update" ).remove();
             $( ".data_entry_delete" ).remove();
             $( '<button type="button" class="btn btn-primary btn-lg data_entry_delete" name="delete" id="delete" title="Delete observation"><span class="glyphicon glyphicon glyphicon-trash"></span></button>' ).prependTo( ".button-delete" );
             $( '<button type="button" class="btn btn-primary btn-lg data_entry_update" name="update" id="update" title="Update observation"><span class="glyphicon glyphicon-floppy-disk"></span></button>' ).prependTo( ".button-observation" );

             $('.data_entry_submit').hide();

	    	var image_folder_name = data.id_record + '_' + data.media_folder_hash;
			var url = gospecies_base_path + '/data/gc_record/' + image_folder_name + '/image';

			$( ".image-box" ).remove();

			 for (var file in data.image) {

				var html    = '<div class="image-box row"><div class="col-sm-6">';


				if (data.image[file].title === null) {
					var title = '';
				} else {
					var title = data.image[file].title;
				}
				html = html + '<div class="form-group">';
				html = html + '<input name="rec_img_title[]" value="'+title+'" type="text" class="form-control" title="Image Title" placeholder="Enter image title"></div>';
				html = html + '<input name="i_id_media[]" type="hidden" value="'+data.image[file].id_media+'" /><input name="i_name[]" type="hidden" value="'+data.image[file].media.file_name+'" />';
				html = html + '<div class="form-group">';
				html = html + '<textarea rows="3" name="i_description[]" class="form-control" placeholder="Enter image description">'+data.image[file].description+'</textarea></div>';
				html = html + '</div><div class="col-sm-6">';
				html = html + '<a href="' + url + '/' + data.image[file].media.file_name + '" target="_blank"><img src="' + url + '/thumbnail/' + data.image[file].media.file_name + '" /></a>';
				html = html + '<br /><a href="#" class="imageremove" id-media="'+data.image[file].id_media+'" file-name="'+data.image[file].media.file_name+'">delete</a></div></div>';

				$(html).appendTo("#images");

			 }

			if (marker) {
			  marker.destroy();
			}

			/* -- add new marker -- */

			marker = new OpenLayers.Layer.Markers( "Markers" );

			var geom      = eval(data.ol_geometry);

			var lonlat_trans = geom.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

			marker.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lonlat_trans.x, lonlat_trans.y)));

			map.addLayer(marker);

			map.setCenter(new OpenLayers.LonLat(geom.x,geom.y), 15);

			$('.tab-observation').html('<span class="glyphicon glyphicon-edit gc_main_tabs_margin"></span>Edit Observation');

			$('#collapseOne').collapse({ parent: '#accordion' }).collapse('show');

          },
          error: function(data) {
             console.log(data);
             alert('Cant get id_record: ' + id_record + '. Try again.');
          }
        });
    });
/***** End - click edit record *******/

/***** Start - click update record *******/
    $(document).on("click",".data_entry_update",function(e){

        e.preventDefault();

        var _id_record          = $('input#id_record').val();
        var _id_attribute_group = $.trim($('#id_attribute_group option:selected').val());
        var _id_project         = $.trim($('#id_project option:selected').val());
        var _id_item            = $('input#id_item').val();
        var _date               = $.trim($('input.data_entry_li_content_date').val());
        var _long_lat           = $.trim($('input#data_entry_li_content_ref').val());

        var _attribute = [];
        var x          = 0;
        var _val       = '';

        for (var i in attribute_group_items) {
			if (attribute_group_items[i].attribute_html_type == 'input') {
				_val = $.trim($('input:text[name=col_' + attribute_group_items[i].attribute_name +  ']').val());
			} else if (attribute_group_items[i].attribute_html_type == 'textarea') {
				_val = $.trim($('textarea[name=col_' + attribute_group_items[i].attribute_name +  ']').val());
			} else if (attribute_group_items[i].attribute_html_type == 'radio') {
				_val = $.trim($('input:radio[name=col_' + attribute_group_items[i].attribute_name +  ']:checked').val());
			} else if (attribute_group_items[i].attribute_html_type == 'select') {
				_val = $.trim($('select[name=col_' + attribute_group_items[i].attribute_name +  '] option:selected').val());
			} else if (attribute_group_items[i].attribute_html_type == 'checkbox') {

				var _val = [];

				$('input:checkbox[name=col_'+ attribute_group_items[i].attribute_name +']:checked').each(function() {
					_val.push($(this).val());
				});
			}

			_attribute[x] = {name : attribute_group_items[i].attribute_name, value : _val};

			x = x + 1;
		}

		var i_name        = [];
		var i_id_media    = [];
		var i_title       = [];
		var i_description = [];
		var _images       = new Object();

		/* get image definitions */

		var x = 0;
		$("input[name^='i_name']").each(function() {

			get_type($(this));
			i_name[x] = $(this).val();

			var _i_id_media = $("input[name^='i_id_media']:eq("+x+")").val();

			if (undefined === _i_id_media) {
				i_id_media[x] = '';
			} else {
				i_id_media[x] = _i_id_media;
			}

			var _i_title = $("input[name^='i_title']:eq("+x+")").val();

			if (undefined === _i_title) {
				i_title[x] = '';
			} else {
				i_title[x] = _i_title;
			}

			var _i_description = $("textarea[name^='i_description']:eq("+x+")").val();

			if (undefined === _i_description) {
				i_description[x] = '';
			} else {
				i_description[x] = _i_description;
			}

			x++;
		});

		_images.i_id_media    = i_id_media;
		_images.i_name        = i_name;
		_images.i_title       = i_title;
		_images.i_description = i_description;

        if (_id_item.length < 16) {
            alert('Select a species name from the dropdown list');
            return;
        }

        if (_date.length < 10) {
            alert('Empty date field or wrong format: Example:  2014-03-24 > year-month-day');
            return;
        }

        if (_long_lat.length < 5) {
            alert('Empty or wrong Geo-Reference: Examples:  50.179343 9.704307 or 50.179343, 9.704307');
            return;
        }

        $('#actiongif').show();

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/json-record-update",
          dataType: "json",
          	data: ({id_record          : _id_record,
          	        id_project         : _id_project,
          	        id_item            : _id_item,
          	        id_attribute_group : _id_attribute_group,
                    date_record_start  : _date,
                    date_record_end    : _date,
                    geom               : _long_lat,
                    attributes         : _attribute,
                    images             : _images}),
          success: function(data) {


			$('.show_record_id').hide();

			var hold_species = $('input#hold_species:checked').val();

			if (hold_species != '1') {
				$('input.ui-autocomplete-input').val('');
				$('input#id_item').val('');
			}
			$('input#data_entry_li_content_abundance').val('1');

			var hold_ref = $('input#hold_ref:checked').val();

			if (hold_ref != '1') {
				$('input#data_entry_li_content_ref').val('');
			}

			$( ".image-box" ).remove();

			$('#actiongif').hide();
			$('#success_message').show();
			$('#success_message').delay( 8000 ).hide(0);

			$('input#id_record').attr('value', '');

			$('.tab-observation').html('<span class="glyphicon glyphicon-plus gc_main_tabs_margin"></span>Add New Observation');

			$('#collapseOne').collapse('hide');
			$('#collapseFour').collapse('show');

			$( ".getrecords" ).trigger( "click" );

          },
          error: function(data) {
             console.log(data);
             alert('Cant get id_record: ' + _id_record + '. Try again.');
          }
        });
    });
/***** End - click update record *******/

/***** Start - clear form *******/

	var clear_form = function() {

		$('input.ui-autocomplete-input').val('');
		$('input#id_item').val('');

		$('input#data_entry_li_content_ref').val('');

		$( ".image-box" ).remove();

		$('#actiongif').hide();
		$('#success_message').show();
		$('#success_message').delay( 8000 ).hide(0);

		$("#observations").trigger("reloadGrid");
		$(".getrecords").trigger("click");

		$( ".data_entry_update" ).remove();
		$( ".data_entry_submit" ).remove();
		$( ".data_entry_delete" ).remove();
		$('.selected_lists > li').remove();
		$('.group-list > li > input').prop('checked', false);
		$( "#data_entry_projectname" ).val('');

		$('.show_record_id').hide();

		$('.tab-observation').html('<span class="glyphicon glyphicon-plus gc_main_tabs_margin"></span>Add New Observation');

		$( '<button type="button" class="btn btn-primary btn-lg data_entry_submit" name="submit" id="submit" title="Save observation"><span class="glyphicon glyphicon glyphicon-floppy-disk"></span></button>' ).prependTo( ".button-observation" );


	};

/***** End - clear form *******/

/***** Start - click reset form *******/
    $(document).on("click","#reset",function(e){

        e.preventDefault();
		$( ".getrecords" ).trigger( "click" );
		$('input#id_record').attr('value', '');
		$('input#id_item').attr('value', '');

		$('input#data_entry_li_content_species').val('');

		$('textarea#data_entry_li_content_comment').val('');
		$('textarea#data_entry_li_content_site_comment').val('');

		$('.show_record_id').hide();

		$( ".image-box" ).remove();

		$('input#data_entry_li_content_ref').val('');

		$('#data_entry_li_content_date').data("DateTimePicker").setDate('');

		$( ".data_entry_update" ).remove();
		$( ".data_entry_submit" ).remove();
		$( ".data_entry_delete" ).remove();
		$('.selected_lists > li').remove();
		$('.group-list > li > input').prop('checked', false);
		$( "#data_entry_projectname" ).val('');

		$('.tab-observation').html('<span class="glyphicon glyphicon-plus gc_main_tabs_margin"></span>Add New Observation');

		$( '<button type="button" class="btn btn-primary btn-lg data_entry_submit" name="submit" id="submit" title="Save observation"><span class="glyphicon glyphicon glyphicon-floppy-disk"></span></button>' ).prependTo( ".button-observation" );

		$(".getrecordattributes").trigger( "click" );

    });
/***** End - click reset form *******/

/***** Start - Remove temporary image *******/

    $(document).on("click",".imageremove",function(e){

    	e.preventDefault();

    	var file     = $(this).attr('file-name');
    	var id_media = $(this).attr('id-media');
    	var relement = $(this).closest( ".image-box" );

	    alert('Remove this image: ' + $(this).attr('file-name') + ' id: ' + id_media);

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/json-record-update/image-remove",
          dataType: "json",
          	data: ({id_media: id_media}),
          success: function(data) {

             relement.remove();
             $("#observations").trigger("reloadGrid");
          },
          error: function(data) {
             console.log(data);
             alert('Cant remove image. Try again.');
          }
        });

    });

/***** End - Remove temporary image *******/

/***** Start - Remove temporary image *******/

    $(document).on("click",".imagedelete",function(e){

    	e.preventDefault();

    	var file     = $(this).attr('file-name');
    	var relement = $(this).closest( ".image-box" );

	    alert($(this).attr('file-name'));

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/json-record-add/image-remove",
          dataType: "json",
          	data: ({image : file}),
          success: function(data) {

             relement.remove();
          },
          error: function(data) {
             console.log(data);
             alert('Cant remove image. Try again.');
          }
        });

    });

/***** End - Remove temporary image *******/

/***** Start - Tabs *******/



/***** End - Tabs *******/

/***** Start - Image sortable *******/

    $( "#images" ).sortable();
    $( "#images" ).disableSelection();

/***** END - Image sortable *******/

/***** Start - Datepicker *******/

 $(function () {
	$('#data_entry_li_content_date').datetimepicker({
		pickTime: false,
		showToday: true,
		useCurrent: true,
		language:'en',
		format: 'yyyy-m-d'
	});

	$('#data_entry_li_content_date').data("DateTimePicker").setDate(current_date);
 });



/***** END - Datepicker *******/


/***** Start - Mapdialog *******/

        // create map container (id=map) and append to document body
        var div = $('<div />')
                    .attr('id', 'map').
                    css({width:400,height:400})
                    .appendTo($('body'));


        // initialize the jQueryUI Dialog
        div.dialog({
            width:450,
            height:500,
            autoOpen: false,
            title: 'My Map',
            resizeStop: function(){
                map.updateSize(); //to prevent drag-zoom error
            },
            dragStop: function(){
                map.updateSize(); //to prevent drag-zoom error
        }});

        $( "#data_entry_li_a_map" ).click(function() {
            $( "#map" ).dialog( "open" );

            map.updateSize();

        });

        $(document).on("click",".show_on_map",function(e) {

			e.preventDefault();

			set_marker_on_map($(this).attr('geom'));

            $( "#map" ).dialog( "open" );

            map.updateSize();

        });

/***** End - Mapdialog *******/


/***** Start - Taxon search *******/

    $( "#data_entry_li_content_species" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          url: gospecies_base_path + "/gospecies/json-taxon-search",
          dataType: "json",
          data: {
              term: request.term,
              id_project: $.trim($('#id_project option:selected').val()),
          },
          success: function( data ) {
              response( data);
          },
          error: function(err ) {
              console.log(err );
          }
        });
      },
      minLength: 2,
            focus: function( event, ui ) {
              $( "#data_entry_li_content_species" ).val( ui.item.label );
              return false;
      },
      select: function( event, ui ) {
              $('#id_item').attr("value", ui.item.id);
        },
        open: function( event, ui ) {
           var x = $( ".ui-menu-item" ).length;

           if (x > 10) {
               $('<li>... mehr</li>').appendTo('ul.ui-autocomplete');
           }
        }
    });
/***** End - Taxon search *******/

/***** Start - set marker on map ***********/

function set_marker_on_map(ol_geometry) {

		/** delete marker if exists **/
		if (marker) {
		  marker.destroy();
		}

		/* -- add new marker -- */

		marker = new OpenLayers.Layer.Markers( "Markers" );

		var geom = eval(ol_geometry);

		var lonlat_trans = geom.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

		marker.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lonlat_trans.x, lonlat_trans.y)));

		map.addLayer(marker);

		map.setCenter(new OpenLayers.LonLat(geom.x,geom.y), 15);

}

/***** End- set marker on map ***********/

/***** Start - Record submit *******/

	function get_type(thing){
	    if(thing===null)return "[object Null]"; // special case
	    return Object.prototype.toString.call(thing);
	}

	$('#actiongif').hide();
	$('#success_message').hide();

	$(document).on("click","#submit",function(e){

		e.preventDefault();

		var _id_project         = $.trim($('#id_project option:selected').val());
        var _id_item            = $.trim($('input#id_item').val());
        var _date               = $.trim($('input.data_entry_li_content_date').val());
        var _long_lat           = $.trim($('input#data_entry_li_content_ref').val());
        var _id_attribute_group = $.trim($('#id_attribute_group option:selected').val());

        var _attribute = [];

        var x = 0;

		for (key in attribute_group_items) {

			if (attribute_group_items[key].attribute_html_type == 'input') {
				$_val = $.trim($('#col_' + attribute_group_items[key].attribute_name).val());
				if ((attribute_group_items[key].required === true) && ($_val == '')) {
					alert('Field "'+attribute_group_items[key].title+'" is empty!');
					return;
			    }
				_attribute[x] = {name : attribute_group_items[key].attribute_name, value : $_val};
			} else if (attribute_group_items[key].attribute_html_type == 'textarea') {
				$_val = $.trim($('#col_' + attribute_group_items[key].attribute_name).val());
				if ((attribute_group_items[key].required === true) && ($_val == '')) {
					alert('Field "'+attribute_group_items[key].title+'" is empty!');
					return;
			    }
				_attribute[x] = {name : attribute_group_items[key].attribute_name, value : $_val};
			} else if (attribute_group_items[key].attribute_html_type == 'select') {
				_attribute[x] = {name : attribute_group_items[key].attribute_name, value : $.trim($('#col_' + attribute_group_items[key].attribute_name +  ' option:selected').val())};
			} else if (attribute_group_items[key].attribute_html_type == 'checkbox') {

				var _tmp = [];

				$('input:checkbox[name=col_'+ attribute_group_items[key].attribute_name +']:checked').each(function() {
					_tmp.push($(this).val());
				});

				_attribute[x] = {name : attribute_group_items[key].attribute_name, value : _tmp};

			} else if (attribute_group_items[key].attribute_html_type == 'radio') {
				_attribute[x] = {name : attribute_group_items[key].attribute_name, value : $.trim($('input:radio[name=col_' + attribute_group_items[key].attribute_name +  ']:checked').val())};
			}
			x = x + 1;
		}

		var i_name        = [];
		var i_title       = [];
		var i_description = [];
		var _images       = new Object();

		/* get image definitions */

		var x = 0;
		$("input[name^='i_name']").each(function() {

			get_type($(this));
			i_name[x] = $(this).val();

			var _i_title = $("input[name^='i_title']:eq("+x+")").val();

			if (undefined === _i_title) {
				i_title[x] = '';
			} else {
				i_title[x] = _i_title;
			}

			var _i_description = $("textarea[name^='i_description']:eq("+x+")").val();

			if (undefined === _i_description) {
				i_description[x] = '';
			} else {
				i_description[x] = _i_description;
			}

			x++;
		});

		_images.i_name        = i_name;
		_images.i_title       = i_title;
		_images.i_description = i_description;

        if (_id_item.length < 16) {
            alert('You have to select a species name from the dropdown list');
            return;
        }

        if (_date.length < 10) {
            alert('Empty or wrong date: Exmaple:  2014-03-24 > year-month-day');
            return;
        }

        if (_long_lat.length < 5) {
            alert('Empty or wrong Geo-Reference: Example:  50.179343 9.704307 or 50.179343, 9.704307');
            return;
        }

        $('#actiongif').show();

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/json-record-add",
          dataType: "json",
          data: ({id_project         : _id_project,
                  id_attribute_group : _id_attribute_group,
			      id_item            : _id_item,
                  date_record_start  : _date,
                  date_record_end    : _date,
                  geom               : _long_lat,
                  attributes         : _attribute,
                  images             : _images
          }),
          success: function(data) {
             clear_form();

          },
          error: function(data) {
              console.log(data);
              alert('error');
              $('#actiongif').hide();
          }
        });
    });

    /***** End - Record submit *******/

    /***** Start - lightbox image viewer *******/

	// delegate calls to data-toggle="lightbox"
	$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
		event.preventDefault();
		return $(this).ekkoLightbox({
			onShown: function() {
				if (window.console) {
					return console.log('Checking our the events huh?');
				}
			}
		});
	});

	/***** End - lightbox image viewer *******/

    $(document).on("click",".pagination a",function(e){

    	e.preventDefault();

    	page     = $(this).html();
    	var dir  = $(this).attr('dir');

    	if (dir == 'next' ) {
			range = range + 5;
			page = range;
		} else if (dir == 'prev' ) {
			if (range > 1) {
				range = range - 5;
		    }
			page = range;
		}

		$( ".getrecords" ).trigger( "click" );

    });



/***** Start - get all record attribute groups *******/

var selected_lists = {};

$(document).on("click","a.check_list",function(e){

    	var id_list = $(this).attr('id_list');
    	var list    = $(this).next().html();

		if (selected_lists[id_list] != 1) {
			selected_lists[id_list] = 1;

			$('.selected_lists').append('<li><input type="checkbox" class="id_list" name="id_list" value="'+id_list+'" checked="checked" title="uncheck to remove this list" /> '+list+' </li>');
		}

});

/***** Start - update project related attribute groups *******/

$(document).on("click","input:checkbox[name=id_group]",function(e){

	var update = $('button').hasClass('updateProject');

	if (update === true) {

		var checked    = $(this).prop('checked');
		var id_group   = $(this).val();
		var id_project = $.trim($('#id_project option:selected').val());

		if (checked === false) {
			var controller = gospecies_base_path + "/gospecies/ajax-remove-project-attribute-group-json";
		} else if (checked === true) {
			var controller = gospecies_base_path + "/gospecies/ajax-add-project-attribute-group-json";
		}

		$.ajax({
		  type: "POST",
		  url: controller,
		  dataType: "json",
			data: ({id_group  : id_group,
					id_project: id_project}),
		  success: function(data) {
		  },
		  error: function(data) {
			 console.log(data);
		  }
		});

	}
});

/***** End - update project related attribute groups *******/

$(document).on("click","input:checkbox[name=id_list]",function(e){

    	var id_list = $(this).val();
        delete selected_lists[id_list];
        $(this).parent().remove();

});

/***** End - get all record attribute groups *******/

var attr_group_opener = -1;

$(document).on("click",".getgroupchilds a",function(e){

    	e.preventDefault();

        if (attr_group_opener == 1) {
            $('.group-list').slideUp("slow");
            attr_group_opener = 0;
            return;
        }

        if (attr_group_opener == 0) {
            $('.group-list').slideDown("slow");
            attr_group_opener = 1;
            return;
        }

        attr_group_opener = 1;

    	var that = $(this);

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-get-attribute-groups-json",
          dataType: "json",
          	data: ({}),
          success: function(data) {

                var group_select = '<ul class="group-list">';
                var has_content = false;

                for (var i in data) {

			    	group_select = group_select + '<li><input type="checkbox" name="id_group" class="id_group" value="' + data[i].id_group + '"><a href="#" id_group="' + data[i].id_group + '">' + data[i].title + '</a></li>';
					has_content = true;
				}

                if (has_content === true) {
					group_select = group_select + '</ul>';

					$(that).after(group_select);
			    }

          },
          error: function(data) {
             console.log(data);

          }
        });

});

$(".getgroupchilds a").trigger( "click" );

/***** Start - get all record attribute groups *******/

var opener = [];
var closer = [];

$(document).on("click",".getlistchilds a.open_list",function(e){

    	e.preventDefault();

    	var id_parent = $(this).attr('id_list');

    	var that = $(this);

    	if ((id_parent === undefined) || (id_parent === '')) {
			id_parent = 0;
		}

        if (closer[id_parent]) {
            $('#p_' + id_parent).next("ul").slideDown("slow");
            closer[id_parent] = null;
            opener[id_parent] = true;
            $('#p_' + id_parent).attr("aria-expanded", "true");
            $('#p_' + id_parent).prev().prev("span").text("- ");
            return;
        }

        if (opener[id_parent]) {
            closer[id_parent] = true;
            $('#p_' + id_parent).next("ul").slideUp("slow");
            $('#p_' + id_parent).attr("aria-expanded", "false");
            $('#p_' + id_parent).prev().prev("span").text("+ ");
            opener[id_parent] = null;
            return;
        }

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-get-list-childs-json",
          dataType: "json",
          	data: ({id_parent: id_parent}),
          success: function(data) {

				opener[id_parent] = true;

                var list_select = '<ul class="species-list">';
                var has_content = false;

                for (var i in data) {

			    	list_select = list_select + '<li class="getlistchilds"><span></span><a href="#" class="check_list" id_list="' + data[i].id_list + '" title="click to add this list"><span class="glyphicon glyphicon-floppy-save"></span></a> <a href="#" class="open_list" id_list="' + data[i].id_list + '" id="p_'+data[i].id_list+'" title="open child lists">' + data[i].title + '</a></li>';
					has_content = true;
				}

                if (has_content === true) {
					list_select = list_select + '</ul>';

					$(that).after(list_select);
			    }

          },
          error: function(data) {
             console.log(data);

          }
        });

});

//$( ".getlistchilds" ).trigger( "click" );

/***** End - get all record attribute groups *******/

/***** Start - clear form *******/

$(document).on("change","#id_project",function(e){

	e.preventDefault();

	var id_project = $.trim($('#id_project option:selected').val());

	if (id_project !== '') {

		$( ".getprojectattributegroups" ).trigger( "click" );
		$('.project_add_edit').html('<a href="#" title="edit project" class="editProjectModal"><span class="glyphicon glyphicon-edit"></span></a>');

	} else {
		$('.attribute-groups').html('This project has no additional attributes or no project selected.');
		$('.additional-attribute').remove();
		$('.project_add_edit').html('<a href="#" title="add project" class="addProjectModal"><span class="glyphicon glyphicon-plus"></span></a>');

	}
});

/***** End - clear form *******/

$(document).on("click",".addProjectModal",function(e){
	$('#addProject').modal('toggle');
	$('h4.modal-title').html('Add Project');
	$( "button.updateProject" ).addClass( "addProject" );
	$( "button.updateProject" ).html( "Add Project" );
	$( "button.updateProject" ).removeClass( "updateProject" );
    $('.selected_lists > li').remove();
    $('.group-list > li > input').prop('checked', false);
	$( "#data_entry_projectname" ).val('');

});

$(document).on("click",".editProjectModal",function(e){

    var id_project = $.trim($('#id_project option:selected').val());

	$('#addProject').modal('toggle');

	$( "button.addProject" ).addClass( "updateProject" );
	$( "button.addProject" ).html( "Update Project" );
	$( "button.addProject" ).removeClass( "addProject" );


	$('h4.modal-title').html('Edit Project');

	var project_name = user_projects[id_project].title;

	$('input[name="projectname"]').val(project_name);

	var attr_groups = user_projects[id_project].attr_groups;

	$('input:checkbox[name="id_group"]').removeAttr('checked');

	for (var i in attr_groups) {
		$('input:checkbox[value="'+attr_groups[i].id_group+'"]').prop('checked',true);
	}

	var lists = user_projects[id_project].lists;

	$('.selected_lists').html('');
	selected_lists = {};

	for (var i in lists) {
		selected_lists[lists[i].id_list] = 1;
		$('.selected_lists').append('<li><input type="checkbox" class="id_list" name="id_list" value="'+lists[i].id_list+'" checked="checked" title="uncheck to remove this list" /> '+lists[i].title+' </li>');
	}


});


/***** Start - get all record attribute groups *******/

var attribute_group_items = [];

$(document).on("click",".getrecordattributes",function(e){

    	e.preventDefault();

		// remove existing attribute fields from dom
    	$('.additional-attribute').remove();

		if (edit_id_attribute_group === 0) {
    		var id_attribute_group = $('#id_attribute_group option:selected').val();
	    } else {
			var id_attribute_group = edit_id_attribute_group;
		}

		edit_id_attribute_group = 0;

    	if (id_attribute_group === undefined) {
			return;
		}

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-get-project-attributes-json",
          dataType: "json",
          	data: ({id_group: id_attribute_group}),
          success: function(data) {

             	var attributes = '';

             	attribute_group_items = data;

				for (var i in data) {

					// get attributes value if assigned (> from edit record)
					var val = at[data[i].attribute_name];

					if ((val === undefined) || (val === null)) {
						val = '';
					}

                	attributes = attributes + '<div class="row additional-attribute">';
                  	attributes = attributes + '<div class="col-xs-1 col-sm-2 col-md-2 col-lg-1">'+data[i].attribute_title+':</div>';
                  	attributes = attributes + '<div class="clearfix visible-xs-block"></div>';
                  	attributes = attributes + '<div class="col-xs-11 col-sm-10 col-md-10 col-lg-11">';
                    attributes = attributes + '<div class="form-group">';

                    if (data[i].attribute_html_type == 'input') {

                      attributes = attributes + '<input type="text" name="col_'+data[i].attribute_name+'" id="col_'+data[i].attribute_name+'" value="'+quoteattr(val)+'" class="form-control input-md">';

					} else if (data[i].attribute_html_type == 'textarea') {

                      attributes = attributes + '<textarea rows="5" name="col_'+data[i].attribute_name+'" id="col_'+data[i].attribute_name+'" class="form-control input-md">'+quoteattr(val)+'</textarea>';

				    } else if (data[i].attribute_html_type == 'select') {

				      attributes = attributes + '<select id="col_'+data[i].attribute_name+'" name="col_'+data[i].attribute_name+'" class="form-control input-md">';

					  var _items = $.parseJSON (data[i].attribute_value);

					  for (var r in _items) {

					  	var sel = '';
					  	if (_items[r].active == '1') {
							sel = ' selected="selected"';
						}



                      	attributes = attributes + '<option value="'+quoteattr(_items[r].value)+'"'+sel+'>'+_items[r].text+'</option>';

				      }
				      attributes = attributes + '</select>';

				    } else if (data[i].attribute_html_type == 'radio') {

					  var _items = $.parseJSON (data[i].attribute_value);

					  for (var r in _items) {

					  	var sel = '';
					  	if (_items[r].active == '1') {
							sel = ' checked="checked"';
						}

					  	if (val == _items[r].text) {
							sel = ' checked="checked"';
						}

                      	attributes = attributes + '<div class="radio"><label><input type="radio" name="col_'+data[i].attribute_name+'" value="'+quoteattr(_items[r].value)+'"'+sel+'>'+_items[r].text+'</label></div>';


				      }
				    } else if (data[i].attribute_html_type == 'checkbox') {

					  var _items = $.parseJSON (data[i].attribute_value);

					  for (var r in _items) {

					  	var sel = '';
					  	if (_items[r].active == '1') {
							sel = ' checked="checked"';
						}

					  	if (val == _items[r].text) {
							sel = ' checked="checked"';
						}

                      	attributes = attributes + '<div class="checkbox"><label><input type="checkbox" name="col_'+data[i].attribute_name+'" value="'+quoteattr(_items[r].value)+'"'+sel+'>'+_items[r].text+'</label></div>';


				      }
				    }

                    attributes = attributes + '</div>';
                  	attributes = attributes + '</div>';
                  	attributes = attributes + '<div class="hidden-xs hidden-sm col-md-3 col-lg-5"></div>';
                	attributes = attributes + '</div>';

				}

				at = [];

				if (attributes > '') {
			    	$('#attributes').after(attributes);
				}

          },
          error: function(data) {
             console.log(data);

          }
        });

});

//$(".getrecordattributes").trigger( "click" );

/***** End - get all record attribute groups *******/

/***** Start - add project *******/

$(document).on("click",".addProject",function(e){

    	e.preventDefault();

    	var id_attr_groups = [];
    	var id_lists       = [];

		$('input.id_list:checked').each(function() {
			id_lists.push($(this).val());
		});

		$('input.id_group:checked').each(function() {
			id_attr_groups.push($(this).val());
		});

    	var project_name   = $.trim($('#data_entry_projectname').val());

    	if (project_name == '') {
			alert('Project name fiels is empty!');
			return;
		}

    	if (id_lists.length == 0) {
			alert('No list selected!');
			return;
		}

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-add-project-json",
          dataType: "json",
          	data: ({project_name   : project_name,
          	        id_lists       : id_lists,
          	        id_attr_groups : id_attr_groups}),
          success: function(data) {

				$('.user-projects').html('');
				$('.getuserprojects').trigger( "click" );
				$('#addProject').modal('hide');

          },
          error: function(data) {
             console.log(data);

          }
        });

});

/***** End - add project *******/

/***** Start - update project *******/

$(document).on("click",".updateProject",function(e){

    	e.preventDefault();

    	var project_name = $.trim($('#data_entry_projectname').val());
    	var id_project   = $.trim($('#id_project option:selected').val());

    	if (project_name == '') {
			alert ('Project name is empty!');
			return;
		}

    	if (id_project == '') {
			alert ('id_project is empty!');
			return;
		}

    	if (Object.keys(selected_lists).length == 0) {
			alert ('No lists selected!');
			return;
		}

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-update-project-json",
          dataType: "json",
          	data: ({id_project   : id_project,
				    project_name : project_name}),
          success: function(data) {

				$('.user-projects').html('');
				$('.getuserprojects').trigger( "click" );
				$('#addProject').modal('hide');

          },
          error: function(data) {
             console.log(data);

          }
        });

});

/***** End - update project *******/

/***** Start - delete species autocomplete value when select a project *******/

$(document).on("change","#id_attribute_group",function(e){

	e.preventDefault();

	$( ".additional-attribute" ).remove();
	$( ".getrecordattributes" ).trigger( "click" );

});

/***** End - delete species autocomplete value *******/

/***** Start - get project attributes groups *******/


$(document).on("click",".getprojectattributegroups",function(e){

		var id_project = $.trim($('#id_project option:selected').val());

		if (id_project == '') {
			$('.attribute-groups').html('This project has no additional attributes or no project selected.');
			return;
		}

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-get-project-attribute-groups-json",
          dataType: "json",
          	data: ({id_project : id_project}),
          success: function(data) {


                var project_select = '';
                var selected       = '';

			    project_select = project_select + '<select class="form-control" id="id_attribute_group" name="id_attribute_group">';

                for (var i in data) {


					if (edit_id_attribute_group !== 0) {
						selected = ' selected="selected"';
					}

			    	project_select = project_select + '<option value="' + data[i].id_group + '"'+selected+'>' + data[i].title + '</option>';

			    	selected = '';

				}

			    project_select = project_select + '</select>';

				$('.attribute-groups').html('');
			    $('.attribute-groups').html(project_select);
				$('.getrecordattributes').trigger( "click" );
          },
          error: function(data) {
             console.log(data);

          }
        });

});

/***** End - get project attributes groups *******/

/***** Start - get species groups *******/

var user_projects = {};

$(document).on("click",".getuserprojects",function(e){

    	e.preventDefault();

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-get-user-projects-json",
          dataType: "json",
          	data: ({}),
          success: function(data) {

                var project_select = '';

			    project_select = project_select + '<select class="form-control" id="id_project" name="id_project">';
			    project_select = project_select + '<option value=""></option>';

			    var page_class = '';

			    user_projects = {};

                for (var i in data) {

					user_projects[data[i].id_project] = {'title'       : data[i].title,
						                                 'attr_groups' : data[i].attr_groups,
					                                     'lists'       : data[i].lists};

			    	project_select = project_select + '<option value="' + data[i].id_project + '">' + data[i].title + '</option>';

			    	page_class = '';
				}

			    project_select = project_select + '</select>';

                project_select = project_select + '<span class="input-group-addon project_add_edit">';
                project_select = project_select + '<a href="#" title="add new project" data-toggle="modal" data-target="#addProject"><span class="glyphicon glyphicon-plus"></span></a>';
                project_select = project_select + '</span>';

			    $('.user-projects').html(project_select);

				$( ".getprojectattributegroups" ).trigger( "click" );

          },
          error: function(data) {
             console.log(data);

          }
        });

});

$( ".getuserprojects" ).trigger( "click" );

/***** End - get species groups *******/

    var page  = 1;
    var limit = 10;
    var range = 1;

/***** Start - new grid *******/
$(".getrecords").click(function(e){

    	e.preventDefault();

        $.ajax({
          type: "POST",
          url: gospecies_base_path + "/gospecies/ajax-search-record-json2",
          dataType: "json",
          	data: ({page: page,
          	        limit: limit,
          	        }),
          success: function(data) {

                var data_table = '';

			    data_table = data_table + '<ul class="pagination"><li><a href="#" dir="prev">&laquo;</a></li>';

			    var page_class = '';

                for (var i = range; i <= (range + 4); i++) {

					if (page == i) {
						page_class = ' class="active"';
					}
			    	data_table = data_table + '<li'+page_class+'><a href="#">'+i+'</a></li>';

			    	page_class = '';
				}

			    data_table = data_table + '<li><a href="#" dir="next">&raquo;</a></li></ul>';

                data_table     = data_table + '<table class="table table-hover">';
                data_table     = data_table + '<thead><tr>';
                data_table     = data_table + '<th>Taxon</th>';
                data_table     = data_table + '<th>Date</th>';
                data_table     = data_table + '<th>Map</th>';
                data_table     = data_table + '<th>Photo</th>';
                data_table     = data_table + '</tr></thead>';
                data_table     = data_table + '<tbody>';

			    for (var i in data) {

					data_table = data_table + '<tr>';
					data_table = data_table + '<td><a href="#" class="edit_record" id_record="' + data[i].id_record + '">' + data[i].item.value + '</a></td>';
					data_table = data_table + '<td>' + formatter_date (data[i].date_record_start) + '</td>';
					data_table = data_table + '<td><a href="#" class="show_on_map" geom="' + data[i].ol_geometry + '">map</a></td>';
					data_table = data_table + '<td>' + formatter_atag_thumb (data[i].image) + '</td>';
					data_table = data_table + '</tr>';

			    }

			    data_table = data_table + ' </tbody></table>';


			    data_table = data_table + '<ul class="pagination"><li><a href="#" dir="prev">&laquo;</a></li>';

			    var page_class = '';

                for (var i = range; i <= (range + 4); i++) {

					page_class = '';

					if (page == i) {
						page_class = ' class="active"';
					}
			    	data_table = data_table + '<li'+page_class+'><a href="#">'+i+'</a></li>';
				}

			    data_table = data_table + '<li><a href="#" dir="next">&raquo;</a></li></ul>';

			    $('#observation_table').html(data_table);

          },
          error: function(data) {
             console.log(data);

          }
        });

    });

    $( ".getrecords" ).trigger( "click" );

/***** End - new grid *******/


// make link of the record_id in observations grid

function formatter_id_record (cellvalue)
{
	return '<a class="edit_record" href="#">'+cellvalue+'</a>';
}

function formatter_date (cellvalue)
{
	return cellvalue.replace(/ [^ ]*$/g, "");
}

function formatter_latlong (cellvalue)
{
	var geom      = eval(cellvalue);
	var latitude  = geom.y;
	var longitude = geom.x;

	return latitude.toFixed(6) + ' ' + longitude.toFixed(6);
}

var _images = [];

var __class_counter = 0;

function formatter_atag_thumb (cellvalue)
{
	var tmp         = '';
	var __class_group = 0;
	var __class       = '';

	/* push image tags of a record */

	for (var i in cellvalue) {

		/* only the first image tag of a record is visible */
		/* we need to include all images of a record > for the bootstrap lightbox plugin */
		tmp = tmp + "<a data-toggle='lightbox' data-gallery='i" + __class_counter + "' class='" + __class + "' href='" + gospecies_base_path + "/data/gc_record/" + cellvalue[i].id_record + "_" + cellvalue[i].media.media_folder_hash + "/image/" + cellvalue[i].media.file_name + "'><img  class='img-responsive' src='" + gospecies_base_path + "/data/gc_record/" + cellvalue[i].id_record + "_" + cellvalue[i].media.media_folder_hash + "/image/thumbnail/" + cellvalue[i].media.file_name + "' width='80' alt='my image' /></a>";

		if (__class_group == 0) {
		  __class_group = 1;
		  __class       = ' i-hidden';
		}

	}

	__class_counter = __class_counter + 1;

	return tmp;
}

});

var map, drawControls;
var marker = null;

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },

    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend(
            {}, this.defaultHandlerOptions
        );
        OpenLayers.Control.prototype.initialize.apply(
            this, arguments
        );
        this.handler = new OpenLayers.Handler.Click(
            this, {
                'click': this.trigger
            }, this.handlerOptions
        );
    },

    trigger: function(e) {
        var lonlat_trans = map.getLonLatFromViewPortPx(e.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));

        /* -- set the latitude and longitude values in the 2 form elements -- */


        OpenLayers.Util.getElement("data_entry_li_content_ref").value  = lonlat_trans.lat.toFixed(6) + ' ' + lonlat_trans.lon.toFixed(6);

	var lonlat = map.getLonLatFromViewPortPx(e.xy);
        /* -- destroy previous marker if present -- */

        if (marker) {
          marker.destroy();
        }

        /* -- add new marker -- */

        marker = new OpenLayers.Layer.Markers( "Markers" );

        marker.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lonlat.lon,lonlat.lat)));

        map.addLayer(marker);
    }

});

function init(){
    //start a simple map, code from on http://openlayers.org/dev/examples/osm.html
    map = new OpenLayers.Map( 'map');

    layer = new OpenLayers.Layer.OSM( "Simple OSM Map");

    var pointLayer = new OpenLayers.Layer.Vector("Point Layer");
    map.addLayers([layer, pointLayer]);

    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.MousePosition());

    var click = new OpenLayers.Control.Click();

    map.addControl(click);
    click.activate();

    map.setCenter(
        new OpenLayers.LonLat(10.690158, 51.241204).transform(
            new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()
            ), 6
        );
}
